package com.xmut.bs.handaccount.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;

import com.xmut.bs.handaccount.R;
import com.xmut.bs.handaccount.adapter.VerifyVideoAdapter;
import com.xmut.bs.handaccount.base.Constants;
import com.xmut.bs.handaccount.base.ToolbarBaseActivity;
import com.xmut.bs.handaccount.bean.ArtContentType;
import com.xmut.bs.handaccount.bean.VideoBean;
import com.xmut.bs.handaccount.bean.VideoEditInfo;
import com.xmut.bs.handaccount.bmob.Article;
import com.xmut.bs.handaccount.util.DisplayUtils;
import com.xmut.bs.handaccount.util.DividerItemDecoration;
import com.xmut.bs.handaccount.util.video.DeviceUtils;
import com.xmut.bs.handaccount.util.video.ExtractFrameWorkThread;
import com.xmut.bs.handaccount.util.video.ExtractVideoInfoUtil;
import com.xmut.bs.handaccount.util.video.PictureUtils;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.UpdateListener;

import static com.xmut.bs.handaccount.base.Constants.PARAM_ARTICLE_ID;
import static com.xmut.bs.handaccount.util.DividerItemDecoration.BOTH_SET;

/**
 * Author Dollkey
 * Date 2018/4/19 17:07.
 */

public class VerifyVideoActivity extends ToolbarBaseActivity {
    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;

    private Article article;
    private ExtractFrameWorkThread mExtractFrameWorkThread;
    private ExtractVideoInfoUtil mExtractVideoInfoUtil;
    private VerifyVideoAdapter mAdapter;

    private final String OutPutFileDirPath = Environment.getExternalStorageDirectory() + "/Extract";

    @Override
    protected String getSubTitle() {
        return "视频审核";
    }

    @Override
    protected int bindLayoutId() {
        return R.layout.activity_verify_video;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setLayoutManager(new GridLayoutManager(mContext, 3));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(mContext,
                DisplayUtils.dp2px(mContext, 8), BOTH_SET, 2, true,
                getResources().getColor(R.color.white)).setHasLeftOrRight(true));
        mAdapter = new VerifyVideoAdapter(mContext,new ArrayList<String>());
        mRecyclerView.setAdapter(mAdapter);
        String path = "";
        for (ArtContentType artContentType : article.getContents()) {
            VideoBean videoBean = artContentType.getVideoBean();
            if (videoBean != null) {
                path = videoBean.getVideoPath();
                break;
            }
        }

        mExtractVideoInfoUtil = new ExtractVideoInfoUtil(path);
        long endPosition = Long.valueOf(mExtractVideoInfoUtil.getVideoLength());
        long startPosition = 0;
        int thumbnailsCount = 12;
        int extractW = (DeviceUtils.getScreenWidth(this)) / 4;
        int extractH = DeviceUtils.dip2px(this, 55);
        mExtractFrameWorkThread = new ExtractFrameWorkThread(
                extractW, extractH, mUIHandler, path,
                OutPutFileDirPath, startPosition, endPosition, thumbnailsCount);
        mExtractFrameWorkThread.start();
    }

    @Override
    protected void initParams(Intent intent) {
        article = (Article) intent.getSerializableExtra(PARAM_ARTICLE_ID);
    }

    @OnClick({R.id.un_pass_btn, R.id.pass_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.un_pass_btn:
                article.setStatus(Constants.VERIFY_FAIL);
                break;
            case R.id.pass_btn:
                article.setStatus(Constants.VERIFY_SUCCESS);
                break;
        }
        article.update(new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    showToast("审核完成");
                    finish();
                } else {
                    showToast("审核失败：" + e.getMessage() + "," + e.getErrorCode());
                }
            }
        });
    }

    private final MainHandler mUIHandler = new MainHandler(this);

    private static class MainHandler extends Handler {
        private final WeakReference<VerifyVideoActivity> mActivity;

        MainHandler(VerifyVideoActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            VerifyVideoActivity activity = mActivity.get();
            if (activity != null) {
                if (msg.what == ExtractFrameWorkThread.MSG_SAVE_SUCCESS) {
                    if (activity.mAdapter != null) {
                        VideoEditInfo info = (VideoEditInfo) msg.obj;
                        activity.mAdapter.addItem(info.path);
                    }
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mExtractVideoInfoUtil.release();
        if (mExtractFrameWorkThread != null) {
            mExtractFrameWorkThread.stopExtract();
        }
        mUIHandler.removeCallbacksAndMessages(null);
        if (!TextUtils.isEmpty(OutPutFileDirPath)) {
            PictureUtils.deleteFile(new File(OutPutFileDirPath));
        }
    }
}
